package com.atwulidun.linkedlist.testSingleLinkedList;

public class Josephu {
    public static void main(String[] args) {
        CircleSingleLinkedList cList = new CircleSingleLinkedList();
        cList.addBoy(5);
        cList.printBoy();
        System.out.println(cList.countBoy());
        cList.delete(2, 3);
    }
}

class CircleSingleLinkedList {
    private Boy first = null;

    public Boy getFirst() {
        return first;
    }

    // 添加Boy的方法
    public void addBoy(int num) {
        if (num < 1) {
            System.out.println("输入参数不合法！");
            return;
        }
        Boy curBoy = null;
        for (int i = 1; i <= num; i++) {
            Boy boy = new Boy(i);
            if (i == 1) {
                first = boy;
                curBoy = boy;
                curBoy.setNext(first);
            } else {
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }
    }

    // 统计boy个数的方法
    public int countBoy() {
        if (first == null) {
            return 0;
        }
        Boy curBoy = first;
        int count = 0;
        do {
            count++;
            curBoy = curBoy.getNext();
        } while (curBoy != first);
        return count;
    }

    // 打印boy的方法
    public void printBoy() {
        if (first == null) {
            System.out.println("boy不存在！");
            return;
        }
        Boy curBoy = first;
        do {
            System.out.println(curBoy.getNo());
            curBoy = curBoy.getNext();
        } while (curBoy != first);
    }

    // 删除boy的方法
    public void delete(int startNo, int countNo) {
        if (startNo < 1 || startNo > countBoy() || countNo < 1 || countNo > countBoy()) {
            System.out.println("输入参数异常！");
            return;
        }
        Boy helper = first;
        while (helper.getNext() != first) {
            helper = helper.getNext();
        }
        for (int i = 1; i < startNo; i++) {
            first = first.getNext();
            helper = helper.getNext();
        }
        while (helper != first) {
            for (int i = 1; i < countNo; i++) {
                first = first.getNext();
                helper = helper.getNext();
            }
            System.out.println("当前被删除的boy编号为：" + first.getNo());
            first = first.getNext();
            helper.setNext(first);
        }
        System.out.println("最后剩余的boy编号为：" + first.getNo());
    }
}

class Boy {
    private int no;
    private Boy next;

    public Boy(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }
}
